"""
前台系统界面 - 现代化版本
"""
import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
from datetime import datetime, timedelta
from core.billing import BillingManager
from core.statistics import StatisticsReport
from .styles import COLORS, FONTS, SPACING, create_card_frame, create_modern_button


class ReceptionPanel:
    """前台系统面板"""
    
    def __init__(self, central_ac):
        self.central_ac = central_ac
        
        self.window = tk.Toplevel()
        self.window.title("前台系统")
        self.window.geometry("1000x800")
        self.window.resizable(True, True)  # 允许调整大小
        self.window.minsize(900, 700)  # 设置最小尺寸
        self.window.configure(bg=COLORS['background'])
        
        # 添加全屏支持（F11切换）
        self.is_fullscreen = False
        self.window.bind('<F11>', self._toggle_fullscreen)
        self.window.bind('<Escape>', self._exit_fullscreen)
        
        self._setup_ui()
        self._configure_styles()
    
    def _configure_styles(self):
        """配置ttk样式"""
        style = ttk.Style()
        
        # 配置Notebook样式
        style.configure(
            'Reception.TNotebook',
            background=COLORS['background'],
            borderwidth=0
        )
        style.configure(
            'Reception.TNotebook.Tab',
            padding=[SPACING['lg'], SPACING['md']],
            font=FONTS['body_bold'],
            background=COLORS['surface']
        )
        style.map(
            'Reception.TNotebook.Tab',
            background=[('selected', COLORS['secondary'])],
            foreground=[('selected', 'white'), ('!selected', COLORS['text_primary'])]
        )
    
    def _setup_ui(self):
        """设置UI界面"""
        # 标题栏
        header_frame = tk.Frame(
            self.window,
            bg=COLORS['secondary'],
            height=90
        )
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)
        
        title_label = tk.Label(
            header_frame,
            text="前台系统",
            font=FONTS['title'],
            bg=COLORS['secondary'],
            fg='white'
        )
        title_label.pack(pady=(SPACING['lg'], SPACING['xs']))
        
        subtitle_label = tk.Label(
            header_frame,
            text="账单管理 • 统计报表 • 数据导出",
            font=FONTS['body'],
            bg=COLORS['secondary'],
            fg='#D1FAE5'
        )
        subtitle_label.pack()
        
        # 主内容区
        content_frame = tk.Frame(
            self.window,
            bg=COLORS['background'],
            padx=SPACING['lg'],
            pady=SPACING['lg']
        )
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 创建笔记本（标签页）
        notebook = ttk.Notebook(content_frame, style='Reception.TNotebook')
        notebook.pack(fill=tk.BOTH, expand=True)
        
        # 账单查询标签页
        bill_frame = tk.Frame(notebook, bg=COLORS['background'])
        notebook.add(bill_frame, text="账单查询")
        self._setup_bill_tab(bill_frame)
        
        # 统计报表标签页
        report_frame = tk.Frame(notebook, bg=COLORS['background'])
        notebook.add(report_frame, text="统计报表")
        self._setup_report_tab(report_frame)
    
    def _setup_bill_tab(self, parent):
        """设置账单查询标签页"""
        # 查询区卡片
        shadow_frame, query_card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.X, padx=SPACING['md'], pady=SPACING['md'])
        query_card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 查询标题
        tk.Label(
            query_card,
            text="查询条件",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 房间号输入区
        input_frame = tk.Frame(query_card, bg=COLORS['card_bg'])
        input_frame.pack(fill=tk.X)
        
        tk.Label(
            input_frame,
            text="房间号:",
            font=FONTS['body_bold'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(side=tk.LEFT, padx=(0, SPACING['md']))
        
        self.bill_room_var = tk.StringVar()
        
        # 自定义输入框样式
        entry_container = tk.Frame(input_frame, bg=COLORS['border'], padx=1, pady=1)
        entry_container.pack(side=tk.LEFT, padx=(0, SPACING['md']))
        
        room_entry = tk.Entry(
            entry_container,
            textvariable=self.bill_room_var,
            font=FONTS['body'],
            width=12,
            relief=tk.FLAT,
            bg=COLORS['surface'],
            fg=COLORS['text_primary'],
            insertbackground=COLORS['primary']
        )
        room_entry.pack(padx=4, pady=4)
        
        # 查询按钮
        query_button = create_modern_button(
            input_frame,
            "查询账单",
            self._query_bill,
            style='info'
        )
        query_button.pack(side=tk.LEFT, padx=(0, SPACING['sm']))
        
        # 导出按钮
        export_button = create_modern_button(
            input_frame,
            "导出账单",
            self._export_bill,
            style='success'
        )
        export_button.pack(side=tk.LEFT)
        
        # 显示区卡片
        shadow_frame2, display_card = create_card_frame(parent)
        shadow_frame2.pack(fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=(0, SPACING['md']))
        display_card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 显示标题
        tk.Label(
            display_card,
            text="账单详情",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 文本显示区
        self.bill_text = scrolledtext.ScrolledText(
            display_card,
            font=('Consolas', 10),
            wrap=tk.WORD,
            height=18,
            relief=tk.FLAT,
            bg='#F9FAFB',
            fg=COLORS['text_primary'],
            insertbackground=COLORS['primary']
        )
        self.bill_text.pack(fill=tk.BOTH, expand=True)
    
    def _setup_report_tab(self, parent):
        """设置统计报表标签页"""
        # 参数区卡片
        shadow_frame, param_card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.X, padx=SPACING['md'], pady=SPACING['md'])
        param_card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 参数标题
        tk.Label(
            param_card,
            text="报表参数",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 时间范围选择
        time_frame = tk.Frame(param_card, bg=COLORS['card_bg'])
        time_frame.pack(fill=tk.X, pady=(0, SPACING['md']))
        
        tk.Label(
            time_frame,
            text="时间范围:",
            font=FONTS['body_bold'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(side=tk.LEFT, padx=(0, SPACING['md']))
        
        self.report_range_var = tk.StringVar(value="24h")
        
        time_options = [
            ("最近24小时", "24h"),
            ("最近7天", "7d"),
            ("最近30天", "30d"),
            ("全部", "all")
        ]
        
        for i, (text, value) in enumerate(time_options):
            btn = tk.Radiobutton(
                time_frame,
                text=text,
                variable=self.report_range_var,
                value=value,
                font=FONTS['body'],
                bg=COLORS['card_bg'],
                fg=COLORS['text_primary'],
                selectcolor=COLORS['card_bg'],
                activebackground=COLORS['card_bg'],
                relief=tk.FLAT,
                padx=SPACING['md'],
                pady=SPACING['xs']
            )
            btn.pack(side=tk.LEFT, padx=(0, SPACING['sm']))
        
        # 按钮区
        button_frame = tk.Frame(param_card, bg=COLORS['card_bg'])
        button_frame.pack(fill=tk.X)
        
        # 生成按钮
        generate_button = create_modern_button(
            button_frame,
            "生成报表",
            self._generate_report,
            style='info'
        )
        generate_button.pack(side=tk.LEFT, padx=(0, SPACING['sm']))
        
        # 导出按钮
        export_button = create_modern_button(
            button_frame,
            "导出报表",
            self._export_report,
            style='success'
        )
        export_button.pack(side=tk.LEFT)
        
        # 显示区卡片
        shadow_frame2, display_card = create_card_frame(parent)
        shadow_frame2.pack(fill=tk.BOTH, expand=True, padx=SPACING['md'], pady=(0, SPACING['md']))
        display_card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 显示标题
        tk.Label(
            display_card,
            text="统计报表",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 文本显示区
        self.report_text = scrolledtext.ScrolledText(
            display_card,
            font=('Consolas', 10),
            wrap=tk.WORD,
            height=18,
            relief=tk.FLAT,
            bg='#F9FAFB',
            fg=COLORS['text_primary'],
            insertbackground=COLORS['primary']
        )
        self.report_text.pack(fill=tk.BOTH, expand=True)
    
    def _query_bill(self):
        """查询账单"""
        room_id = self.bill_room_var.get().strip()
        
        if not room_id:
            messagebox.showwarning("⚠️ 警告", "请输入房间号")
            return
        
        # 补充前导零
        if room_id.isdigit():
            room_id = f"{int(room_id):03d}"
        
        room_state_dict = self.central_ac.get_room_state(room_id)
        
        if not room_state_dict:
            messagebox.showerror("✗ 错误", f"房间 {room_id} 不存在")
            return
        
        # 获取房间状态对象
        room_state = self.central_ac.room_states.get(room_id)
        if not room_state:
            messagebox.showerror("✗ 错误", "无法获取房间状态")
            return
        
        # 生成账单
        bill = BillingManager.generate_bill(room_state)
        details = BillingManager.generate_detail_list(room_state)
        text = BillingManager.format_bill_text(bill, details)
        
        # 显示账单
        self.bill_text.delete('1.0', tk.END)
        self.bill_text.insert('1.0', text)
    
    def _export_bill(self):
        """导出账单"""
        room_id = self.bill_room_var.get().strip()
        
        if not room_id:
            messagebox.showwarning("⚠️ 警告", "请输入房间号")
            return
        
        # 补充前导零
        if room_id.isdigit():
            room_id = f"{int(room_id):03d}"
        
        room_state = self.central_ac.room_states.get(room_id)
        if not room_state:
            messagebox.showerror("✗ 错误", f"房间 {room_id} 不存在")
            return
        
        try:
            filename = BillingManager.export_bill_to_file(room_state)
            messagebox.showinfo("✓ 成功", f"账单已导出到文件:\n{filename}")
        except Exception as e:
            messagebox.showerror("✗ 错误", f"导出失败: {e}")
    
    def _generate_report(self):
        """生成报表"""
        time_range = self.report_range_var.get()
        
        # 计算时间范围
        end_time = datetime.now()
        if time_range == "24h":
            start_time = end_time - timedelta(hours=24)
        elif time_range == "7d":
            start_time = end_time - timedelta(days=7)
        elif time_range == "30d":
            start_time = end_time - timedelta(days=30)
        else:  # all
            start_time = datetime(2000, 1, 1)
        
        # 生成报表
        report = StatisticsReport.generate_report(
            self.central_ac.room_states,
            start_time,
            end_time
        )
        text = StatisticsReport.format_report_text(report)
        
        # 显示报表
        self.report_text.delete('1.0', tk.END)
        self.report_text.insert('1.0', text)
    
    def _export_report(self):
        """导出报表"""
        time_range = self.report_range_var.get()
        
        # 计算时间范围
        end_time = datetime.now()
        if time_range == "24h":
            start_time = end_time - timedelta(hours=24)
        elif time_range == "7d":
            start_time = end_time - timedelta(days=7)
        elif time_range == "30d":
            start_time = end_time - timedelta(days=30)
        else:  # all
            start_time = datetime(2000, 1, 1)
        
        try:
            filename = StatisticsReport.export_report_to_file(
                self.central_ac.room_states,
                start_time,
                end_time
            )
            messagebox.showinfo("✓ 成功", f"报表已导出到文件:\n{filename}")
        except Exception as e:
            messagebox.showerror("✗ 错误", f"导出失败: {e}")
    
    def _toggle_fullscreen(self, event=None):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        self.window.attributes('-fullscreen', self.is_fullscreen)
    
    def _exit_fullscreen(self, event=None):
        """退出全屏"""
        self.is_fullscreen = False
        self.window.attributes('-fullscreen', False)
    
    def show(self):
        """显示窗口"""
        self.window.mainloop()
